<script setup lang="ts">
import type { Product } from '@/types/mall'
import { formatPrice, formatTime } from '@/utils/mall'

const cartStore = useCartStore()

// 收藏列表
const favorites = ref<Product[]>([])
const loading = ref(false)
const isEditMode = ref(false)
const selectedItems = ref<Set<string>>(new Set())

// 模拟收藏数据
const mockFavorites: Product[] = [
  {
    id: '1',
    name: 'iPhone 15 Pro Max',
    description: '全新iPhone 15 Pro Max，搭载A17 Pro芯片，钛金属设计',
    categoryId: '11',
    images: ['https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-naturaltitanium-pdp-image-position-1a_CN.jpg'],
    defaultPrice: 999900,
    originalPrice: 1099900,
    sales: 1200,
    stock: 50,
    status: 'active',
    rating: 4.8,
    reviewCount: 520,
    tags: ['新品', '热销'],
    createdAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(),
    updatedAt: new Date().toISOString(),
  },
  {
    id: '2',
    name: 'MacBook Air M3',
    description: '搭载M3芯片的MacBook Air，轻薄便携，性能卓越',
    categoryId: '21',
    images: ['https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/macbook-air-13-m3-midnight-pdp-image-position-1_CN.jpg'],
    defaultPrice: 899900,
    originalPrice: 999900,
    sales: 800,
    stock: 30,
    status: 'active',
    rating: 4.9,
    reviewCount: 350,
    tags: ['推荐'],
    createdAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString(),
    updatedAt: new Date().toISOString(),
  },
  {
    id: '3',
    name: 'AirPods Pro 3',
    description: '全新AirPods Pro，主动降噪更出色，音质更佳',
    categoryId: '14',
    images: ['https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/airpods-pro-2nd-gen-hero-select-202209_FMT_WHH.jpg'],
    defaultPrice: 189900,
    originalPrice: 219900,
    sales: 2000,
    stock: 100,
    status: 'active',
    rating: 4.7,
    reviewCount: 850,
    tags: ['热销', '推荐'],
    createdAt: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString(),
    updatedAt: new Date().toISOString(),
  },
]

// 获取收藏列表
async function getFavoriteList() {
  try {
    loading.value = true
    
    // TODO: 调用API获取收藏列表
    // const response = await api.favorite.getFavoriteList()
    // favorites.value = response.data
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    favorites.value = mockFavorites
  } catch (error) {
    console.error('获取收藏列表失败:', error)
    uni.showToast({ title: '获取收藏失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

// 跳转到商品详情
function goToProductDetail(productId: string) {
  uni.navigateTo({ url: `/subPackages/product-package/goodsDetail/index?id=${productId}` })
}

// 添加到购物车
async function addToCart(product: Product) {
  try {
    const success = await (cartStore as any).addToCart(product)
    if (success) {
      uni.vibrateShort()
    }
  } catch (error) {
    console.error('添加到购物车失败:', error)
    uni.showToast({ title: '添加到购物车失败', icon: 'none' })
  }
}

// 取消收藏
async function removeFavorite(productId: string) {
  try {
    // TODO: 调用API取消收藏
    // await api.favorite.removeFavorite(productId)
    
    // 更新本地数据
    const index = favorites.value.findIndex(item => item.id === productId)
    if (index > -1) {
      favorites.value.splice(index, 1)
    }
    
    uni.showToast({ title: '已取消收藏', icon: 'success' })
  } catch (error) {
    console.error('取消收藏失败:', error)
    uni.showToast({ title: '操作失败', icon: 'none' })
  }
}

// 切换编辑模式
function toggleEditMode() {
  isEditMode.value = !isEditMode.value
  if (!isEditMode.value) {
    selectedItems.value.clear()
  }
}

// 切换选中状态
function toggleSelect(productId: string) {
  if (selectedItems.value.has(productId)) {
    selectedItems.value.delete(productId)
  } else {
    selectedItems.value.add(productId)
  }
}

// 全选/取消全选
function toggleSelectAll() {
  if (selectedItems.value.size === favorites.value.length) {
    selectedItems.value.clear()
  } else {
    selectedItems.value = new Set(favorites.value.map(item => item.id))
  }
}

// 批量删除
function batchDelete() {
  if (selectedItems.value.size === 0) {
    uni.showToast({ title: '请先选择商品', icon: 'none' })
    return
  }

  uni.showModal({
    title: '删除收藏',
    content: `确定要删除选中的${selectedItems.value.size}个商品吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          // TODO: 调用API批量删除
          // await api.favorite.batchRemoveFavorite([...selectedItems.value])
          
          // 更新本地数据
          favorites.value = favorites.value.filter(item => !selectedItems.value.has(item.id))
          selectedItems.value.clear()
          isEditMode.value = false
          
          uni.showToast({ title: '删除成功', icon: 'success' })
        } catch (error) {
          console.error('批量删除失败:', error)
          uni.showToast({ title: '删除失败', icon: 'none' })
        }
      }
    }
  })
}

// 批量添加到购物车
async function batchAddToCart() {
  if (selectedItems.value.size === 0) {
    uni.showToast({ title: '请先选择商品', icon: 'none' })
    return
  }

  try {
    const selectedProducts = favorites.value.filter(item => selectedItems.value.has(item.id))
    
    for (const product of selectedProducts) {
      await (cartStore as any).addToCart(product)
    }
    
    selectedItems.value.clear()
    isEditMode.value = false
    
    uni.showToast({ title: `已添加${selectedProducts.length}件商品到购物车`, icon: 'success' })
    uni.vibrateShort()
  } catch (error) {
    console.error('批量添加到购物车失败:', error)
    uni.showToast({ title: '添加失败', icon: 'none' })
  }
}

// 计算折扣
function calculateDiscount(product: Product) {
  if (!product.originalPrice || product.originalPrice <= product.defaultPrice) {
    return null
  }
  return Math.round((1 - product.defaultPrice / product.originalPrice) * 10)
}

// 页面生命周期
onMounted(() => {
  getFavoriteList()
})
</script>

<template>
  <view class="favorite-page">
    <!-- 头部 -->
    <view class="favorite-header">
      <view class="header-title">
        <text class="title">我的收藏</text>
        <text v-if="favorites.length > 0" class="count">({{ favorites.length }})</text>
      </view>
      
      <view v-if="favorites.length > 0" class="header-actions">
        <text class="edit-btn" @click="toggleEditMode">
          {{ isEditMode ? '完成' : '编辑' }}
        </text>
      </view>
    </view>

    <!-- 收藏列表 -->
    <view v-if="loading" class="loading-container">
      <wd-loading size="24px" />
      <text>加载中...</text>
    </view>

    <view v-else-if="favorites.length === 0" class="empty-state">
      <wd-icon name="star-on" size="60px" color="#ddd" />
      <text class="empty-text">暂无收藏商品</text>
      <text class="empty-desc">快去收藏一些喜欢的商品吧</text>
      <wd-button type="primary" size="large" @click="uni.redirectTo({ url: '/pages/index/index' })">
        去逛逛
      </wd-button>
    </view>

    <view v-else class="favorite-content">
      <!-- 全选 -->
      <view v-if="isEditMode" class="select-all-section">
        <view class="select-all" @click="toggleSelectAll">
          <wd-checkbox :value="selectedItems.size === favorites.length && favorites.length > 0" />
          <text class="select-all-text">全选</text>
        </view>
        
        <text class="selected-count">已选择{{ selectedItems.size }}件</text>
      </view>

      <!-- 商品列表 -->
      <view class="product-list">
        <view
          v-for="product in favorites"
          :key="product.id"
          class="product-item"
        >
          <!-- 选择框 -->
          <view v-if="isEditMode" class="item-checkbox" @click="toggleSelect(product.id)">
            <wd-checkbox :value="selectedItems.has(product.id)" />
          </view>

          <!-- 商品内容 -->
          <view class="product-content" @click="goToProductDetail(product.id)">
            <!-- 商品图片 -->
            <image :src="product.images[0]" class="product-image" mode="aspectFit" />

            <!-- 商品信息 -->
            <view class="product-info">
              <text class="product-name">{{ product.name }}</text>
              <text class="product-desc">{{ product.description }}</text>
              
              <!-- 标签 -->
              <view v-if="product.tags && product.tags.length > 0" class="product-tags">
                <text
                  v-for="tag in product.tags"
                  :key="tag"
                  class="tag"
                >
                  {{ tag }}
                </text>
              </view>
              
              <view class="product-price">
                <text class="current-price">{{ formatPrice(product.defaultPrice) }}</text>
                <text v-if="product.originalPrice && product.originalPrice > product.defaultPrice" class="original-price">
                  {{ formatPrice(product.originalPrice) }}
                </text>
                <view v-if="calculateDiscount(product)" class="discount-tag">
                  {{ calculateDiscount(product) }}折
                </view>
              </view>

              <view class="product-stats">
                <view class="rating">
                  <wd-icon name="star-on" size="12px" color="#ffc107" />
                  <text>{{ product.rating }}</text>
                </view>
                <text class="sales">已售{{ product.sales }}+</text>
                <text class="collect-time">{{ formatTime(product.createdAt, 'MM-DD') }}收藏</text>
              </view>
            </view>
          </view>

          <!-- 操作按钮 -->
          <view v-if="!isEditMode" class="product-actions">
            <wd-button
              type="info"
              size="small"
              @click="removeFavorite(product.id)"
            >
              取消收藏
            </wd-button>
            
            <wd-button
              type="primary"
              size="small"
              @click="addToCart(product)"
            >
              加购物车
            </wd-button>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view v-if="isEditMode && favorites.length > 0" class="bottom-actions">
      <view class="action-info">
        <view class="select-all" @click="toggleSelectAll">
          <wd-checkbox :value="selectedItems.size === favorites.length && favorites.length > 0" />
          <text class="select-text">全选</text>
        </view>
      </view>
      
      <view class="action-buttons">
        <wd-button
          type="warning"
          size="large"
          :disabled="selectedItems.size === 0"
          @click="batchDelete"
        >
          删除({{ selectedItems.size }})
        </wd-button>
        
        <wd-button
          type="primary"
          size="large"
          :disabled="selectedItems.size === 0"
          @click="batchAddToCart"
        >
          加入购物车({{ selectedItems.size }})
        </wd-button>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.favorite-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100px;
}

.favorite-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: white;
  margin-bottom: 10px;

  .header-title {
    display: flex;
    align-items: center;
    gap: 4px;

    .title {
      font-size: 18px;
      font-weight: bold;
      color: #333;
    }

    .count {
      font-size: 14px;
      color: #666;
    }
  }

  .header-actions {
    .edit-btn {
      font-size: 14px;
      color: var(--wot-color-theme);
    }
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  gap: 15px;
  font-size: 14px;
  color: #666;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100px 20px;

  .empty-text {
    margin: 20px 0 8px;
    font-size: 16px;
    color: #333;
  }

  .empty-desc {
    margin-bottom: 30px;
    font-size: 14px;
    color: #999;
  }
}

.favorite-content {
  .select-all-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background: white;
    margin-bottom: 10px;

    .select-all {
      display: flex;
      align-items: center;
      gap: 8px;

      .select-all-text {
        font-size: 14px;
        color: #333;
      }
    }

    .selected-count {
      font-size: 14px;
      color: #666;
    }
  }

  .product-list {
    background: white;

    .product-item {
      display: flex;
      align-items: center;
      padding: 15px;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .item-checkbox {
        margin-right: 10px;
      }

      .product-content {
        flex: 1;
        display: flex;
        margin-right: 10px;

        .product-image {
          width: 80px;
          height: 80px;
          border-radius: 8px;
          margin-right: 12px;
          background: #f8f9fa;
        }

        .product-info {
          flex: 1;

          .product-name {
            font-size: 14px;
            color: #333;
            font-weight: 500;
            display: -webkit-box;
            -webkit-line-clamp: 1;
            -webkit-box-orient: vertical;
            overflow: hidden;
            margin-bottom: 4px;
          }

          .product-desc {
            font-size: 12px;
            color: #999;
            display: -webkit-box;
            -webkit-line-clamp: 1;
            -webkit-box-orient: vertical;
            overflow: hidden;
            margin-bottom: 6px;
          }

          .product-tags {
            display: flex;
            gap: 4px;
            margin-bottom: 6px;

            .tag {
              font-size: 10px;
              color: #ff4142;
              border: 1px solid #ff4142;
              border-radius: 2px;
              padding: 1px 4px;
            }
          }

          .product-price {
            display: flex;
            align-items: center;
            gap: 6px;
            margin-bottom: 6px;

            .current-price {
              font-size: 16px;
              font-weight: bold;
              color: #ff4142;
            }

            .original-price {
              font-size: 12px;
              color: #999;
              text-decoration: line-through;
            }

            .discount-tag {
              font-size: 10px;
              color: #ff4142;
              background: #fff5f5;
              border: 1px solid #ff4142;
              border-radius: 2px;
              padding: 1px 4px;
            }
          }

          .product-stats {
            display: flex;
            align-items: center;
            gap: 12px;

            .rating {
              display: flex;
              align-items: center;
              gap: 2px;
              font-size: 11px;
              color: #666;
            }

            .sales,
            .collect-time {
              font-size: 11px;
              color: #999;
            }
          }
        }
      }

      .product-actions {
        display: flex;
        flex-direction: column;
        gap: 8px;

        :deep(.wd-button) {
          min-width: 70px;
        }
      }
    }
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  background: white;
  padding: 15px;
  border-top: 1px solid #f0f0f0;
  z-index: 10;

  .action-info {
    .select-all {
      display: flex;
      align-items: center;
      gap: 8px;

      .select-text {
        font-size: 14px;
        color: #333;
      }
    }
  }

  .action-buttons {
    flex: 1;
    display: flex;
    gap: 15px;
    margin-left: 20px;

    :deep(.wd-button) {
      flex: 1;
    }
  }
}
</style>

<route lang="json">
{
  "name": "favoriteList",
  "style": {
    "navigationBarTitleText": "我的收藏"
  }
}
</route>